package jym.tan.tmdb.method.get;

import java.net.URL;

import jym.tan.tmdb.TMDB;
import jym.tan.tmdb.bean.wrapper.PersonSearchWrapper;
import jym.tan.tmdb.constant.TMDBConstants;
import jym.tan.tmdb.method.Base;

/**
 * The Class SearchPeople. This class is similar to the <b>Search People</b> method described in 
 * <a href="http://help.themoviedb.org/kb/api/search-people">Search People</a>.
 * This method is used to search people in TMDb and iterate through the search results.
 * @author Tanmoy
 */
public class SearchPeople extends Base {

	/**
	 * Instantiates a new SearchPeople.
	 *
	 * @param tmdb 
	 * 		An instance of the {@link TMDB} class
	 */
	public SearchPeople(TMDB tmdb) {
		super(tmdb, TMDBConstants.SEARCH_PERSON);
	}

	/**
	 * Search for a movie with the help of given parameters and return a {@link PersonSearchWrapper} object.
	 *
	 * @param personName 
	 * 		The person name - the query param is your search text. It works best when the text has been 
	 * 		properly escaped.
	 * @param page 
	 * 		Some searches will have more than 20 results, the default number of items returned per page. 
	 * 		To iterate through use the page parameter.
	 * @param allResults 
	 * 		Some searches will have more than 20 results. So the value 
	 * 		of <code>allResults</code> toggle whether or not the <code>PersonSearchWrapper</code> 
	 * 		object contains all search results
	 * @return 
	 * 		The <code>PersonSearchWrapper</code> object
	 * @throws Exception 
	 * 		If any kind off exception occurred
	 */
	public PersonSearchWrapper search(String personName, int page, boolean allResults) throws Exception {
		URL searchURL = getUrl(personName, page);
		PersonSearchWrapper wrapper = getJsonObject(searchURL, PersonSearchWrapper.class);
		return allResults ? search(wrapper, personName) : wrapper;
	}

	/**
	 * Search for all results of a given movie search.
	 *
	 * @param wrapper 
	 * 		The <code>PersonSearchWrapper</code> object
	 * @param personName 
	 * 		The person name - the query param is your search text. It works best when the text has been 
	 * 		properly escaped.
	 * @return 
	 * 		The <code>PersonSearchWrapper</code> object
	 * @throws Exception
	 * 		If any kind off exception occurred
	 */
	private PersonSearchWrapper search(PersonSearchWrapper wrapper, String personName) throws Exception {
		if (wrapper.getTotalPages() == 1) {
			return wrapper;
		}

		for (int i = 2; i <= wrapper.getTotalPages(); i++) {
			URL searchURL = getUrl(personName, i);
			Thread.sleep(2000);
			PersonSearchWrapper movieSearchWrapper = getJsonObject(searchURL, PersonSearchWrapper.class);
			wrapper.getResults().addAll(movieSearchWrapper.getResults());
		}
		
		return wrapper;
	}
}
